<template>
  <div class="meal-package-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-bar">
      <div class="search-left">
        <el-input
            v-model="searchQuery"
            placeholder="请输入套餐名称"
            clearable
            style="width: 240px; margin-right: 15px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>

        <el-select
            v-model="selectedCategory"
            placeholder="选择套餐分类"
            clearable
            style="width: 180px"
            @change="handleCategoryChange"
        >
          <el-option
              v-for="category in setMealCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
      </div>

      <div class="search-right">
        <el-button type="danger" :disabled="!selectedSetMeal.length" @click="batchDelete">
          批量删除
        </el-button>
        <el-button
            type="success"
            :disabled="!selectedSetMeal.length"
            @click="batchUpdateStatus(1)"
        >
          批量起售
        </el-button>
        <el-button
            type="warning"
            :disabled="!selectedSetMeal.length"
            @click="batchUpdateStatus(0)"
        >
          批量停售
        </el-button>
        <el-button type="primary" @click="navigateToAddDish">
          <el-icon><Plus /></el-icon>新建套餐
        </el-button>
      </div>
    </div>

    <!-- 套餐列表 -->
    <el-table
        :data="setMealList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="name" label="套餐名称" width="200" align="center"/>
      <el-table-column label="套餐图片" width="150" align="center">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px"
              :src="getFullImageUrl(row.image)"
              :preview-src-list="[getFullImageUrl(row.image)]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
          />
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="套餐分类" width="200" align="center"/>
      <el-table-column prop="price" label="售价(元)" width="150" align="center">
        <template #default="{row}">
          {{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="售卖状态" width="100" align="center">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '在售' : '停售' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"/>
      <el-table-column label="操作" width="220" align="center">
        <template #default="{row}">
          <el-button size="small" @click="navigateToEditDish(row.id)">修改</el-button>
          <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? '停售' : '起售' }}
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <Pagination
        :currentPage="currentPage"
        :pageSize="pageSize"
        :total="total"
        @update:currentPage="handlePageChange"
        @update:pageSize="handlePageSizeChange"
    />

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Plus, Search} from "@element-plus/icons-vue";
import Pagination from "@/components/common/Pagination.vue";
import {useRouter} from "vue-router";
import {fileViewPath} from "@/utils/file";
import {getCategoryByType} from "@/api/category";
import {deleteSetMeal, deleteSetMealById, getSetMealList} from "@/api/setmeal";
import {updateBatchStatus} from "@/api/setmeal";

const router = useRouter()
const loading = ref(false)//加载状态
// 数据状态
const setMealCategories = ref([])//套餐分类数组
const selectedCategory = ref('')
const searchQuery = ref('')
const setMealList = ref([])//套餐列表数组
const selectedSetMeal = ref([])//选中的套餐

//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

//图片访问路径
const getFullImageUrl = (imagePath) =>{
  if(!imagePath) return '';
  return `${fileViewPath}${formatImagePath(imagePath)}`
}

const loadSetMealCategories = async () => {
  try{
    const res = await getCategoryByType(2)
    if(res.code === '200'){
      setMealCategories.value = res.data
    }else{
      ElMessage.error('获取套餐分类失败')
    }
  }catch (error){
    ElMessage.error('获取套餐分类失败')
  }
}

// 路径格式化函数（处理Windows路径）
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/'); // 将反斜杠替换为斜杠
};

// 加载套餐列表
const loadSetMeal = async () => {
  if(loading.value) return;
  loading.value = true;
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value,
      categoryId: selectedCategory.value
    }

    const res = await getSetMealList(params);
    if(res.code === '200'){
      setMealList.value = res.data.records
      total.value = res.data.total;
    }else{
      ElMessage.error(res.msg || '获取套餐列表失败')
    }
  } catch (error) {
    ElMessage.error('获取套餐列表失败')
  } finally {
    loading.value = false
  }
}

//处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadSetMeal()
}

//分类筛选变化
const handleCategoryChange = () =>{
  currentPage.value = 1
  loadSetMeal()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedSetMeal.value = selection.map(item => item.id)
}

// 批量删除
const batchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的菜品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const submitDeleteIds = {
      ids:selectedSetMeal.value
    }
    const res = await deleteSetMeal(submitDeleteIds)
    if (res.code === '200') {
      ElMessage.success(`成功删除${selectedSetMeal.value.length}项`)
      selectedSetMeal.value = []
      await loadSetMeal()
    }else{
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {})
}

// 批量更新状态
const batchUpdateStatus = async (status) => {
  try {
    const submitFormData = {
      ids:selectedSetMeal.value,
      status:status
    }
    const res = await updateBatchStatus(submitFormData)

    if (res.code === '200') {
      ElMessage.success(status === 1 ? '已批量起售' : '已批量停售')
      await loadSetMeal()
      selectedSetMeal.value = []
    }else{
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 单个套餐状态切换
const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  try {
    const submitFormData = {
      ids:[row.id],
      status:newStatus
    }
    const res = await updateBatchStatus(submitFormData)
    if (res.code === '200') {
      ElMessage.success(newStatus === 1 ? '已起售' : '已停售')
      await loadSetMeal()
    }else{
      ElMessage.error( '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 单个删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该菜品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteSetMealById(id);
    if (res.code === '200') {
      ElMessage.success(res.data||'删除成功')
      await loadSetMeal()
    }else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {})
}

// 导航到添加页面
const navigateToAddDish = () => {
  router.push('/setmeal/add')
}

// 导航到编辑页面
const navigateToEditDish = (id) => {
  router.push(`/setmeal/edit/${id}`)
}

// 分页处理函数
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadSetMeal()
};
const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 必须重置页码
  loadSetMeal()
};

// 初始化加载数据
onMounted(async () => {
  await loadSetMeal();
  await loadSetMealCategories();
})
</script>

<style scoped>
.meal-package-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-left {
  display: flex;
}

.search-right {
  display: flex;
  gap: 10px;
}

.search-filter-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.left-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.right-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 10px;
}

.el-image {
  cursor: pointer;
  transition: transform 0.3s;
}
.el-image:hover {
  transform: scale(1.05);
}
</style>